package com.exam.service.serviceImpl;

import com.exam.dataobject.ExaminationAnswer;
import com.exam.dataobject.ExaminationResult;
import com.exam.dataobject.mapper.ExaminationContentMapper;
import com.exam.repository.ExaminationAnswerRepository;
import com.exam.repository.ExaminationResultRepository;
import com.exam.service.ExaminationAnswerService;
import com.exam.utils.RedisUserIdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by v
 * Date:2019/2/23
 * Time:16:04
 */
@Service
public class ExaminationAnswerServiceImpl implements ExaminationAnswerService {

    @Autowired
    private ExaminationAnswerRepository examinationAnswerRepository;

    @Autowired
    private ExaminationResultRepository examinationResultRepository;

    @Autowired
    private ExaminationContentMapper examinationContentMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public void inputAnswer(Map<Object, Object> map, HttpServletRequest request) {

        Integer userId = Integer.valueOf(RedisUserIdUtil.getUserId(request, redisTemplate));

        Integer examinationId = Integer.valueOf(map.get("examinationId").toString());

        List<ExaminationAnswer> examinationAnswerList = new ArrayList<>();
        List<Integer> examinationContentIds = examinationContentMapper.getExaminationContentIds(examinationId);
        Integer answerScore = 0;

        for (Integer i : examinationContentIds){
            //试卷内容编号
            String str_i = i.toString();
            ExaminationAnswer examinationAnswer = new ExaminationAnswer();

            examinationAnswer.setExaminationContentId(i);
            //答案
            String answer = map.get(str_i).toString();
            examinationAnswer.setAnswer(answer);
            examinationAnswer.setUserId(userId);

            examinationAnswerList.add(examinationAnswer);

            //计算得分
            Map<Object, Object> rightMap = examinationContentMapper.getQuestionRightOptions(i);
            if (answer.equals(rightMap.get("opRights").toString()))
                answerScore += Integer.valueOf(rightMap.get("score").toString());
        }
        examinationAnswerRepository.saveAll(examinationAnswerList);

        //保存考试结果
        ExaminationResult examinationResult = new ExaminationResult();
        examinationResult.setUserId(userId);
        examinationResult.setExaminationId(examinationId);
        examinationResult.setAnswerScore(answerScore);
        examinationResultRepository.save(examinationResult);
    }
}
